﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;

using AnyOffice.DAL;
using AnyOffice.Components;

namespace AnyOffice.Web.general.netdiskGX
{
    public partial class diskfolder : ModulePage
    {
        private readonly DiskGXDao bll = new DiskGXDao();
        private readonly DiskTypeGXDao dbll = new DiskTypeGXDao();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["strsql"] != null)
                {
                    Bindrep("", Request.QueryString["strsql"].ToString()); //查询
                }
                else
                {
                    Bindrep("", "");
                }
                Bindtree(tree_Path.Nodes);
            }
        }


        /// <summary>
        /// 节点绑定
        /// </summary>
        public void Bindtree(TreeNodeCollection Nds)
        {
            string id = Session["Readid"].ToString().Trim(','); //可读取的文件柜父id
            string[] idarr = id.Split(',');
            for (int i = 0; i < idarr.Count(); i++)
            {
                List<AnyOffice.Model.DiskGX> disk = bll.GetListByparentId(base.Conn, " DiskID =" + idarr[i] + " order by Seq asc");
                foreach (Model.DiskGX d in disk)
                {
                    TreeNode pnode = new TreeNode();
                    pnode.Value = d.DiskID.ToString();
                    pnode.Text = d.Name;
                    pnode.ImageUrl = "/images/files/folder.gif";
                    Nds.Add(pnode);
                    BindChilds(d.DiskID.ToString(), d.DiskTypeID.ToString(), pnode.ChildNodes);
                }
            }
        }


        /// <summary>
        /// 绑定节点
        /// </summary>
        /// <param name="pid">父节点</param>
        /// <param name="disktype">类型</param>
        /// <param name="Nds">对象集合</param>
        public void BindChilds(string pid, string disktype, TreeNodeCollection Nds)
        {
            List<AnyOffice.Model.DiskGX> disk = bll.GetListByparentId(base.Conn, " ParentDiskID=" + pid + " and DiskTypeID=" + disktype + " and FileTypeID=1 order by [Name]");
            foreach (Model.DiskGX d in disk)
            {
                TreeNode pnode = new TreeNode();
                pnode.Value = d.DiskID.ToString();
                pnode.Text = d.Name;
                pnode.ImageUrl = "/images/files/folder.gif";
                Nds.Add(pnode);
                BindChilds(pnode.Value, disktype, pnode.ChildNodes);
            } this.tree_Path.ExpandDepth = 1;
        }

        /// <summary>
        /// 表格数据绑定
        /// </summary>
        /// <param name="pid">父节点</param>
        /// <param name="strsql">查询条件</param>
        public void Bindrep(string pid, string strsql)
        {
            string id = Session["Readid"].ToString().Trim(',');
            string tid = Session["Readtid"].ToString().Trim(',');
            if (id.IndexOf(',') != -1)
            {
                id = id.Substring(0, id.IndexOf(","));
            }
            if (tid.IndexOf(",") != -1)
            {
                tid = tid.Substring(0, tid.IndexOf(","));
            }
            if (pid == "" && strsql == "")
            {
                strsql = " ParentDiskID=" + id + " and DiskTypeID=" + tid + " order by FileTypeID";
                Session["homeDiskID"] = id;
                Session["Cdid"] = id;
                labCurent.Text = bll.GetParentPath(base.Conn, id, "");
            }
            else
            {
                if (strsql != "")
                {
                    strsql = strsql + " and DiskTypeID=" + tid + " order by FileTypeID";
                    labCurent.Text = bll.GetParentPath(base.Conn, id, "");
                }
                if (pid != "")
                {
                    strsql = " ParentDiskID=" + pid + " order by FileTypeID";
                    labCurent.Text = bll.GetParentPath(base.Conn, pid, "");
                }
            }
            this.rep_pfile.DataSource = bll.GetList(base.Conn, strsql);
            rep_pfile.DataBind();
        }

        /// <summary>
        /// 图标
        /// </summary>
        /// <param name="tid">类型</param>
        public string GetType(string tid)
        {
            string str = "";
            FileTypeDao ftype = new FileTypeDao();
            AnyOffice.Model.FileType mode = ftype.GetModel(base.Conn, Convert.ToInt32(tid));
            if (mode.ICO != "")
            {
                str = "<img src='../../../" + mode.ICO + "' alt=''/>";
            }
            return str;
        }

        /// <summary>
        /// 文件列表事件
        /// </summary>
        protected void rep_pfile_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string comId = e.CommandArgument.ToString();
            Label lablbtn = (Label)e.Item.FindControl("lablbtn");
            string[] arr = lablbtn.CssClass.Split(',');
            if (e.CommandName == "dow")
            {
                Model.DiskTypeGX dt = dbll.GetModel(base.Conn, Convert.ToInt32(arr[3]));
                string path = bll.GetParentPath(base.Conn, comId, "");
                string filepath = dt.BasePath + "\\" + path;
                if (File.Exists(filepath))
                {
                    Download(filepath, arr[1]);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, typeof(string), "addclass", "<script>alert('文件不存在！');</script>", false);
                }
            }
            if (e.CommandName == "see")
            {
                if (arr[2] == "1")
                {
                    Session["Cdid"] = comId;
                    Bindrep(comId, "");
                }
                else
                {
                    return;
                }
            }
        }

        /// <summary>   
        /// 文件下载   
        /// </summary>
        /// <param name="FullFileName">物理路径</param>
        private void Download(string FullFileName, string filename)
        {
            FileInfo DownloadFile = new FileInfo(FullFileName);
            Response.Clear();
            Response.ClearHeaders();
            Response.Buffer = false;
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
            Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
            Response.WriteFile(DownloadFile.FullName);
            Response.Flush();
            Response.End();
        }


        /// <summary>
        /// 文件列表绑定初始化
        /// </summary>
        protected void rep_pfile_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            //文件大小
            Label labsize = (Label)e.Item.FindControl("lablSize");
            //初始按钮
            Label lablbtn = (Label)e.Item.FindControl("lablbtn");
            string[] arr = lablbtn.CssClass.Split(',');
            if (arr[1].IndexOf("doc") != -1 || arr[1].IndexOf("xls") != -1 || arr[1].IndexOf("ppt") != -1)
            {
                //阅读
                lablbtn.Text += "<a href=\"#\" onclick=\"window.open('../publicfile/index.aspx?attachment_id=" + arr[0] + "&name=" + Server.UrlEncode(arr[1]) + "&op=0',null,'menubar=0,toolbar=0,status=1,scrollbars=1,width='+ screen.availWidth+',height='+screen.availHeight+',resizable=1');\">阅读</a>";

            }

            if (arr[2] != "1")
            {
                string[] aa = Session["isdow"].ToString().Trim(',').Split(',');
                if (aa.Contains(Session["homeDiskID"].ToString()))
                {
                    LinkButton dow = (LinkButton)e.Item.FindControl("lbtn_dow");
                    dow.Visible = true;
                }
            }
            else
            {
                labsize.Text = bll.GetfolderSize(base.Conn, labsize.CssClass).ToString();
            }
        }


        /// <summary>
        /// 向上
        /// </summary>
        protected void ibtn_up_Click(object sender, ImageClickEventArgs e)
        {
            if (Session["Readid"] != null)
            {
                string[] arr = Session["Readid"].ToString().Split(',');
                if (arr.Contains(Session["Cdid"].ToString())) //判断是否到跟目录
                {
                    Bindrep(Session["Cdid"].ToString(), "");
                    Session["homeDiskID"] = Session["Cdid"].ToString();
                }
                else
                {
                    Model.DiskGX d = bll.GetModel(base.Conn, Convert.ToInt64(Session["Cdid"].ToString()));
                    if (d != null)
                    {
                        if (d.ParentDiskID != 0)
                        {
                            Bindrep(d.ParentDiskID.ToString(), "");
                            Session["Cdid"] = d.ParentDiskID.ToString();
                            labCurent.Text = bll.GetParentPath(base.Conn, d.ParentDiskID.ToString(), "");
                        }
                        else
                        {
                            Session["homeDiskID"] = d.DiskID.ToString();//当前根目录重置
                            Session["Cdid"] = d.DiskID.ToString();
                            Bindrep(d.DiskID.ToString(), "");
                            labCurent.Text = bll.GetParentPath(base.Conn, d.DiskID.ToString(), "");
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 根目录
        /// </summary>
        protected void Ibtn_Home_Click(object sender, ImageClickEventArgs e)
        {
            if (Session["homeDiskID"] != null)
            {
                rep_pfile.DataSource = null;
                labCurent.Text = bll.GetModel(base.Conn, Convert.ToInt64(Session["homeDiskID"].ToString())).Name;
                Bindrep(Session["homeDiskID"].ToString(), "");
                //点击根目录当前目录也就等于更目录
                Session["Cdid"] = Session["homeDiskID"].ToString();
            }
        }

        /// <summary>
        /// 刷新 
        /// </summary>
        protected void Imbtn_resh_Click(object sender, ImageClickEventArgs e)
        {
            Bindrep(Session["Cdid"].ToString(), "");
        }

        /// <summary>
        /// 保存当前顶层根目录
        /// </summary>
        protected void tree_Path_SelectedNodeChanged(object sender, EventArgs e)
        {
            if (tree_Path.SelectedValue != "")
            {
                Model.DiskGX d = bll.GetModel(base.Conn, Convert.ToInt64(tree_Path.SelectedValue));
                if (d.ParentDiskID == 0)//是否到顶层
                {
                    Session["homeDiskID"] = tree_Path.SelectedValue; //当前根目录
                }
                else
                {
                    //获得跟节点
                    int id = bll.GetLeveID(base.Conn, tree_Path.SelectedValue);
                    if (id != -1)
                    {
                        Session["homeDiskID"] = id;
                    }

                }
                Session["Cdid"] = tree_Path.SelectedValue;
                labCurent.Text = bll.GetParentPath(base.Conn, tree_Path.SelectedValue, "");
                Bindrep(tree_Path.SelectedValue, "");
            }
        }

    }
}